﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;

using edowork.com.SQL2005;
using edowork.com.Model;

namespace WebInvoicingsys.system.storage.productarrange
{
    public partial class storageadj_check_check : System.Web.UI.Page
    {
        //前台输出提示信息变量
        public string alert_msg = "", Total_qty1 = "0", Total_qty2 = "0";

        //传入的参数
        string id, start_date, end_date, ljid;

        private void getTotal()
        {
            Total_qty1 = ((storageadj_product_class)Session["storageadj_out"]).Total_qty1.ToString();
            Total_qty2 = ((storageadj_product_class)Session["storageadj_out"]).Total_qty2.ToString();
        }

        /// <summary>
        /// 取得传入的参数
        /// </summary>
        /// <returns></returns>
        private bool GetParma()
        {
            try
            {
                id = Request.Params["id"].ToString();
                start_date = Request.Params["start_date"].ToString();
                end_date = Request.Params["end_date"].ToString();
                ljid = Request.Params["ljid"].ToString();
            }
            catch
            {
                //显示出错信息
                alert_msg = String.Format(Scripts.alert_warning, Errormsg.er_Parampost);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return false;
            }

            return true;
        }

        //绑定单据主信息
        private void BindInfo()
        {
            Execute exec = new Execute(Session["connectionString"].ToString());

            string sql = "", error_msg = "";

            //取得传入的参数
            if (GetParma() == false)
            {
                return;
            }

            //构造SQL语句
            sql = @"select  a.ljid,
                            a.billdate,
                            a.warehouseid,
                            (select warehouse.warehousename from warehouse where a.warehouseid=warehouse.warehouseid) warehousename,
                            a.sysdate,
	                        (select sysuser.username from sysuser where sysuser.userid=a.userid) username,
	                        a.remark,
	                        a.checkstu,
	                        (select sysuser.username from sysuser where sysuser.userid=a.checkuserid) checkusername,
	                        a.Checkdate,
	                        a.checkremark,
	                        a.m_stu
                        from Library_adj a
                        where a.ljid= '{0}'";

            sql = String.Format(sql, id);

            DataSet ds = exec.ExecSQLQueryDataSet(sql, ref error_msg);

            if ((ds == null) || (ds.Tables.Count <= 0) || (ds.Tables[0].Rows.Count <= 0))
            {
                alert_msg = String.Format(Scripts.alert_warning, error_msg);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return;
            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                hfwarehouseid.Value = dr["warehouseid"].ToString();
                hfbilldate.Value = dr["billdate"].ToString();

                txt_billdate.Text = dr["billdate"].ToString();
                txt_warehousename.Text = dr["warehousename"].ToString();
                txt_remark.Text = dr["remark"].ToString();

            }
        }

        //绑定Session中的货品数据
        private void Bind()
        {
            DataTable dtList = new DataTable();

            dtList.Columns.Add("dgvID");
            dtList.Columns.Add("id");
            dtList.Columns.Add("areaname_out");
            dtList.Columns.Add("storagename_out");
            dtList.Columns.Add("areaname_in");
            dtList.Columns.Add("storagename_in");
            dtList.Columns.Add("productcode");
            dtList.Columns.Add("productname");
            dtList.Columns.Add("productshortname");
            dtList.Columns.Add("goodsclassname");
            dtList.Columns.Add("goodsunitname");
            dtList.Columns.Add("goodsspecname");
            dtList.Columns.Add("stackname");
            dtList.Columns.Add("guardname");
            dtList.Columns.Add("qty1");
            dtList.Columns.Add("qty2");

            DataTable dtData = ((storageadj_product_class)Session["storageadj_out"]).getList().Copy();

            foreach (DataRow dr in dtData.Rows)
            {
                DataRow drnew = dtList.NewRow();

                drnew["dgvID"] = (dtList.Rows.Count + 1).ToString();
                drnew["id"] = dr["id"].ToString();
                drnew["areaname_out"] = dr["areaname_out"].ToString();
                drnew["storagename_out"] = dr["storagename_out"].ToString();
                drnew["areaname_in"] = dr["areaname_in"].ToString();
                drnew["storagename_in"] = dr["storagename_in"].ToString();
                drnew["productcode"] = dr["productcode"].ToString();
                drnew["productname"] = dr["productname"].ToString();
                drnew["productshortname"] = dr["productshortname"].ToString();
                drnew["goodsclassname"] = dr["goodsclassname"].ToString();
                drnew["goodsunitname"] = dr["goodsunitname"].ToString();
                drnew["goodsspecname"] = dr["goodsspecname"].ToString();
                drnew["stackname"] = dr["stackname"].ToString();
                drnew["guardname"] = dr["guardname"].ToString();
                drnew["qty1"] = dr["qty1"].ToString();
                drnew["qty2"] = dr["qty2"].ToString();

                dtList.Rows.Add(drnew);
            }

            rplist.DataSource = dtList;
            rplist.DataBind();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ;
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetParma();

                try
                {
                    ((storageadj_product_class)Session["storageadj_out"]).Reset();
                }
                catch
                {
                    Session.Add("storageadj_out", new storageadj_product_class(Session["connectionString"].ToString()));
                }
                finally
                {
                    ((storageadj_product_class)Session["storageadj_out"]).getDataList(id);
                }

                BindInfo();

                Bind();

                getTotal();
            }
        }

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (GetParma() == false)
            {
                return;
            }

            alert_msg = "";

            //保存数据入数据库
            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch (Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "";
                int result = -1;

                //更新主表的审批备注
                sql = "update Library_adj set checkremark='{1}' where ljid='{0}' and checkstu='0' and m_stu='0'";

                sql = String.Format(sql, id, txt_checkremark.Text.Trim());

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "调整单备注保存失败，错误原因：调整单的状态已变化。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }


                tran.Commit();
                tranutil.CloseConnection();
            }

            alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Save);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
        }

        //返回
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            GetParma();

            string url = "/system/storage/productarrange/storageadj_check_list.aspx?start_date={0}&end_date={1}&ljid={2}";

            url = String.Format(url, start_date, end_date, ljid);

            Response.Redirect(url);
        }

        //审核
        protected void btnCheck_Click(object sender, EventArgs e)
        {
            if (GetParma() == false)
            {
                return;
            }

            alert_msg = "";

            //保存数据入数据库
            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch (Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "", error_msg = "";
                int result = -1;
                DataSet dsResult = null;

                //检查当前选择的年份与月份是否在结算日期之前
                sql = String.Format("select * from (select isnull(max(years+months), '') dates from sys_monthly_main) a where a.dates >='{0}{1}'", DateTime.Parse(hfbilldate.Value).ToString("yyyy"), DateTime.Parse(hfbilldate.Value).ToString("MM"));

                dsResult = exec.ExecSQLQueryDataSet(sql, ref alert_msg, tran);

                if ((dsResult == null) || (dsResult.Tables[0].Rows.Count > 0))
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "当前选择的月份在结算日期之后。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //检查是否存在盘点单
                sql = String.Format("select csid from check_stock where warehouseid=(select warehouseid from Library_adj where ljid='{0}') and checkstu='0'", id);

                dsResult = exec.ExecSQLQueryDataSet(sql, ref alert_msg, tran);

                if ((dsResult == null) || (dsResult.Tables[0].Rows.Count > 0))
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "当前仓库正在盘点，不能进行出入库操作。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //锁定所有需操作的表资源，同时写入不存在仓库库存表中的库存产品，写入库存流水，更新库存数量
                sql = String.Format("exec sys_storageadj_check_locktable '{0}'", id);

                dsResult = exec.ExecStoreProcQueryDataSet(sql, ref error_msg, tran);

                if (dsResult == null)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, error_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //更新仓库单审核人员信息
                sql = "update Library_adj set checkuserid='{1}', checkstu='1', Checkdate='{2}', checkremark='{3}' where ljid='{0}' and m_stu='0' and checkstu='0'";

                sql = String.Format(sql, id, Session["userid"].ToString(), DateTime.Now.ToString("yyyy-MM-dd"), txt_checkremark.Text.Trim());

                result = exec.ExecSQLQueryInt(sql, ref error_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "调整单审批失败，错误原因：调整单的状态已变化。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                tran.Commit();
                tranutil.CloseConnection();
            }


            alert_msg = String.Format(Scripts.alert_success, Errormsg.stockbill_in_check_success);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
        }
    }
}